/**
 * Description:
 * Class Name:LockAccount
 * Date:2022/5/7 9:26
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第16章_多线程._16_5_同步线程._16_5_5_同步锁Lock;

import java.util.concurrent.locks.ReentrantLock;

public class LockAccount {
    // 定义锁对象
    private final ReentrantLock lock = new ReentrantLock();
    // 封装账户编号、账户余额的两个成员变量
    private String accountNo;
    private double balance;
    public LockAccount(){}
    public LockAccount(String accountNo, double balance){
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public String getAccountNo() {
        return accountNo;
    }
    // 不为balance提供setter方法
    public double getBalance() {
        return balance;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        LockAccount account = (LockAccount) o;
        return account.getAccountNo().equals(getAccountNo());
    }

    @Override
    public int hashCode() {
        return accountNo.hashCode();
    }

    // 提供一个线程安全的draw()方法来完成取钱操作
    public void draw(double drawAmount){
        // 加锁
        lock.lock();
        try {
            if (balance >= drawAmount){
                // 吐出钞票
                System.out.println("取钱成功！吐出钞票：" + drawAmount + " 元");
                try {
                    Thread.sleep(1);
                }
                catch (InterruptedException e){
                    e.printStackTrace();
                }
                // 修改余额
                balance -= drawAmount;
                System.out.println("\t余额为：" + balance);
            }
            else {
                System.out.println(Thread.currentThread().getName() + " 抱歉，余额不足！");
            }
        }
        finally {
            // 修改完成，释放锁
            lock.unlock();
        }
    }
}
